﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zhongchouwwwww.Models;
using Zhongchouwwwww.BAL;

namespace Zhongchouwwwww.webform
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public static string idd = "";
        public static Userinfo Userinfo = new Userinfo();
        public static Returnsetinfo Returns = new Returnsetinfo();
        public static CollectionInfo Collec = new CollectionInfo();
        public static ProjectinfoDTO ProjectDate = new ProjectinfoDTO();
        public static List<Projectinfo> proje = new List<Projectinfo>();
        public static List<ReturnsetinfoDTO> returnsetinfos = new List<ReturnsetinfoDTO>();
        public static int useid = 0;
        public static string[] urls = new string[3];
        public int Oun;
        public static Projectinfo a = new Projectinfo();
        public static List<CommentInfoDTO> comments = new List<CommentInfoDTO>();
        public static Dictionary<string, List<string>> commentsNameImgs = new Dictionary<string, List<string>>();
        public static List<CommentInfoDTO> _tocomments = new List<CommentInfoDTO>();
        public static string ThisUserImgs = "";
        public static string ThisUserName = "";
        public static int ThisProjectPro = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            useid = Config.Config.ThisUser.UserId;
            ThisUserImgs = Config.Config.ThisUser.UserImg;
            ThisUserName = Config.Config.ThisUser.UserName;
            if (!IsPostBack)
            {
                string id = Request.QueryString["id"];
                if (id == null)//处理非法跳转
                    Response.Redirect("Index1.aspx");
                idd = id;
                returnsetinfos.Clear();//刷新数据
                using (ZhongchouDBEntities db = new ZhongchouDBEntities())
                {
                    //根据传入的项目ID 获取发起人ID
                    string sql = $"select userid from Projectinfo where projectid='{idd}'";
                    var ProUserID = db.Database.SqlQuery<int>(sql).FirstOrDefault();
                    //根据获取到的发起人ID获取用户名
                    string sqlname = $"select usernikename from Userinfo where userid='{ProUserID}'";
                    var UserName = db.Database.SqlQuery<string>(sqlname).FirstOrDefault();
                    //用户名赋值
                    Userinfo.usernikename = UserName;
                    //回报与支持
                    string Ret = $"select * from Returnsetinfo where projectid='{idd}'";
                    var Retnum = db.Database.SqlQuery<Returnsetinfo>(Ret);
                    foreach (var itecm in Retnum)
                    {
                        returnsetinfos.Add(回报表数据提取转换(itecm));
                    }
                    Rrojectitem.DataSource = returnsetinfos;
                    Rrojectitem.DataBind();
                    //项目表
                    string sqe = $"select * from Projectinfo where projectid = '{idd}'";
                    var Date = db.Database.SqlQuery<Projectinfo>(sqe);
                    foreach (var item in Date)
                    {
                        GetData(item);
                    }
                    //收藏表
                    string sqee = $"select COUNT(*) from CollectionInfo where projectid= '{idd}' and supportmoney <> '0'";
                    var INTYYY = db.Database.SqlQuery<int>(sqee);//支持人数
                    foreach (var item in INTYYY)
                    {
                        ZCZRS.Text = item.ToString();
                    }
                    string sqret = $"select COUNT(*) from CollectionInfo where projectid= '{idd}' and supportmoney = '0'";
                    var INTYYYer = db.Database.SqlQuery<int>(sqret);//喜欢人数
                    foreach (var item in INTYYYer)
                    {
                        XHRS.Text = item.ToString();
                    }
                    //评论表
                    string sqlcom = $"select * from CommentInfo where projectid = '{idd}'";
                    var comDate = BAL.GetDate.GetCommentInfoDates(sqlcom);
                    comments = comDate.Where(ae => {
                        if (ae.tocommentid == 0 && ae.Touserid ==0)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }).ToList();
                    _tocomments = comDate.Where(ae => {
                        if (ae.tocommentid == 0 && ae.Touserid == 0)
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }).ToList();
                    //根据用户id获取用户名称和头像  添加首次评论的内容
                    commentsNameImgs.Clear();
                    for (int i = 0; i < comments.Count; i++)
                    {
                        string name = db.Database.SqlQuery<string>($"select usernikename from Userinfo where userid = {comments[i].Userid}").First();
                        string img = db.Database.SqlQuery<string>($"select imgurl from Userinfo where userid = {comments[i].Userid}").First();
                        commentsNameImgs.Add(comments[i].Commentvalues,
                        new List<string>()  { comments[i].Commentid.ToString(), img, name, comments[i].Userid, comments[i].PastTime, } );
                    }
                    //commentsNameImgs数据结构 ：   key：评论  values：List<string> 
                    //第一是此评论的评论ID 0
                    //第二是用户名头像  
                    //第三是用户昵称
                    //第四是此评论来着哪个用户  用户id 3
                    //第五是此评论发送时间  已格式化后
                    //第六是此评论的回复用户名
                    //第七是此评论的回复详情值
                    //第八是此评论的回复发送时间
                    for (int i = 0; i < _tocomments.Count; i++)
                    {
                        foreach (var item in commentsNameImgs.Values)
                        {
                            if (_tocomments[i].tocommentid.ToString() == item[0] && _tocomments[i].Touserid.ToString() == item[3])
                            {
                                var aa = BAL.GetDate.db.Userinfo.Where(ac => ac.userid == int.Parse(_tocomments[i].Userid)).FirstOrDefault();
                                if (aa!=null)
                                {
                                    item.Add(aa.usernikename);
                                }
                                else
                                {
                                    item.Add("用户用户");
                                }
                                item.Add(_tocomments[i].Commentvalues);
                                item.Add(_tocomments[i].PastTime);
                            }
                        }
                    }
                };
            }
            
        }




        //回报信息
        private static ReturnsetinfoDTO 回报表数据提取转换(Returnsetinfo item)
        {
            return new ReturnsetinfoDTO()
            {
                supportmoney = item.supportmoney,//获取金额
                number = item.number,//回报名额
                returncontent = item.returncontent,//回报内容
                time = item.time,//天数
                freight = item.freight,//邮费
            };
        }
        private static Projectinfo Pmeng(Projectinfo inti)
        {
            Projectinfo ne = new Projectinfo
            {
                incomemoney = inti.incomemoney
            };
            return ne;
        }

        //赋值
        public static void GetData(Projectinfo item)
        {
            int pro = 0;
            if (1 > (((double)(item.incomemoney % item.targetmoney) / item.targetmoney) * 100))
            {
                pro = 1;
            }
            else if (0 == (int)(((double)(item.incomemoney % item.targetmoney) / item.targetmoney) * 100))
            {
                if (item.incomemoney == 0)
                {
                    pro = 0;
                }
                else
                {
                    pro = 100;
                }
            }
            else
            {
                pro = (int)(((double)(item.incomemoney % item.targetmoney) / item.targetmoney) * 100);
            }
            urls = item.showimgurl.Split(new char[] { '?' });
            DateTime now = DateTime.Now;
            DateTime last = ((DateTime)item.createdate).AddDays(item.time);
            ProjectDate.projectname = item.projectname;//名字
            ProjectDate.projectadd = item.projectadd;//项目地址
            ProjectDate.projectdesc = item.projectdesc;//简介
            ProjectDate.aboutus = item.aboutus;//关于我们
            ProjectDate.incomemoney = item.incomemoney;//目前收到金额
            ProjectDate.wanttodo = item.wanttodo;//想做什么
            ProjectDate.need = item.need;//需要支持
            ProjectDate.promise = item.promise;//回报
            ProjectDate.typer = item.type;//分类
            ProjectDate.targetmoney = item.targetmoney;//目标金额
            ProjectDate.projectlabel = item.projectlabel;//自定义标签
            ProjectDate.progress = pro;//进度条
            ProjectDate.remainingday = new TimeSpan(now.Ticks - last.Ticks).Days * -1;//剩余天数
            ProjectDate.EndData = ((DateTime)item.createdate).AddDays(item.time);//项目截至时间
            ProjectDate.state = item.state;//项目状态
            ThisProjectPro = ProjectDate.progress;
        }
        protected void ButZC_Click(object sender, EventArgs e)
        {
            //登录状态判断
            if (BAL.DataVerification.IsSignin())
            {
                try
                {
                    int JE = int.Parse(ZC_JE.Text);
                    ProjectDate.incomemoney += JE;
                    string sqlll = $"insert CollectionInfo values('{Config.Config.ThisUser.UserId}','{idd}',{JE})";
                    string sqljin = $"update Projectinfo set incomemoney = incomemoney+{JE} where projectid={idd}";
                    if (BAL.GetDate.EXEXE(sqlll) && BAL.GetDate.EXEXE(sqljin))
                    {
                        Response.Write("<script>alert('支持项目成功')</script>");
                        ZC_JE.Enabled = false;
                    }
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('您输入的支持金额不合法')</script>");

                }
            }
            else
            {
                Response.Redirect("user-login.aspx");
                //直接跳转到登陆页面
                //未登录状态
            }

        }
        protected void ButXH_Click(object sender, EventArgs e)
        {
            //登录状态判断
            if (!BAL.DataVerification.IsSignin())
                Response.Redirect("user-login.aspx");
            try
            {
                //尝试去拿关于该用户和该项目的收藏表记录  取的是喜欢记录的收藏表ID
                int reslut = BAL.GetDate.db.Database.SqlQuery<int>($"select collectionid from CollectionInfo where userid={useid} and projectid = {idd} and supportmoney = 0").First();
            }
            catch (Exception)
            {
                //添加喜欢和该项目的收藏数到数据库
                try
                {
                    string sqlll = $"insert CollectionInfo values('{useid}','{idd}',0)";
                    string sql2 = $"update Projectinfo set collection = collection+1 where projectid={idd}";
                    if (BAL.GetDate.EXEXE(sqlll) && BAL.GetDate.EXEXE(sql2))
                    {
                        Response.Write("<script>alert('此项目已成功添加到我的喜欢！')</script>");
                        ButXH.Enabled = false;
                        return;
                    }
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('添加喜欢失败')</script>");
                }
            }
            Response.Write("<script>alert('你已经添加过此项目至我的喜欢！不可重复添加')</script>");
        }
  

        protected void Rrojectitem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            //登录状态判断
            if (BAL.DataVerification.IsSignin())
            {
                try
                {
                    int p = returnsetinfos[0].supportmoney / returnsetinfos[0].number;
                    ProjectDate.incomemoney += returnsetinfos[0].jine;
                    string sqlly = $"insert CollectionInfo values({useid},{idd},{p})";
                    string sqlongp = $"update Projectinfo set incomemoney +={p} where projectid={idd}";
                    if (BAL.GetDate.EXEXE(sqlly) && BAL.GetDate.EXEXE(sqlongp))
                    {
                        Response.Write("<script>alert('支持成功')</script>");
                    }
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('支持失败')</script>");
                    throw;
                }
            }
            else
            {
                Response.Redirect("user-login.aspx");
                //直接跳转到登陆页面
                //未登录状态
            }
        }

        protected void SendComment_Click(object sender, EventArgs e)
        {
            foreach (var item in commentsNameImgs)
            {
                if (ThisUserMsg.Text == item.Key && useid == int.Parse(item.Value[2]))
                {
                    ThisUserMsg.Text = "";
                    Response.Write("<script>alert('你已发布过此评论')</script>");
                    return;
                }

            }
            
            if (BAL.GetDate.EXEXE($"insert into CommentInfo Values('{ThisUserMsg.Text}', '{useid}', '{idd}', '0', '{DateTime.Now}','0')"))
            {
                Response.Write("<script>alert('发布评论成功！')</script>");
                Response.Redirect($"Project.aspx?id={idd}");
            }
            else
            {
                return;
            }
        }

        protected void Unnamed_Click(object sender, EventArgs e)
        {

        }

        protected void btnHF_Click(object sender, EventArgs e)
        {

        }
    }
}